'use strict';
const db=uniCloud.database()
const dbCmd = db.command
exports.main = async (event, context) => {
	const {
		user_id,
		article_id
	} = event
	
	const user = await db.collection('user').doc(user_id).get()
	const thumbs_up_article_ids = user.data[0].thumbs_up_article_ids
	
	const article = await db.collection('article').doc(article_id).get()
	let thumbs_up = article.data[0].thumbs_up_count
	
	console.log("thumbs_up:",thumbs_up)
	
	let thumbs_ids = null
	if(thumbs_up_article_ids.includes(article_id)){
		return{
			code:200,
			message:"您已经点过赞了",
			data:thumbs_up
		}
	}else{	
		thumbs_ids = dbCmd.addToSet(article_id)
	}
	
	await db.collection('user').doc(user_id).update({
		thumbs_up_article_ids:thumbs_ids
	})
	
	//更新点赞数量
	await db.collection('article').doc(article_id).update({
		//inc 原子操作，减少一次请求（在原基础上加 1）
		thumbs_up_count:dbCmd.inc(1)
	})
	const article1 = await db.collection('article').doc(article_id).get()
	const thumbs_up1 = article1.data[0].thumbs_up_count
	console.log("thumbs_up1:",thumbs_up1)
	
	//返回数据给客户端
	return {
		code:200,
		message:"点赞成功",
		data:thumbs_up1
	}
};
